import Util from "../utils/util.js";
import {SaveSkuInfo,WriteSkuInfo} from './webStorage.js'


//这个函数在整个wps加载项中是第一个执行的
function OnAddinLoad(ribbonUI) {

    if (typeof (Application.ribbonUI) != "object") {
        Application.ribbonUI = ribbonUI
    }
    if (typeof (Application.Enum) != "object") { // 如果没有内置枚举值
        Application.Enum = Util.WPS_Enum
    }
    return true
}


function copyFile() {
    const field = window.localStorage.getItem('field')?Number(window.localStorage.getItem('field')):3
    const start = window.localStorage.getItem('start')?Number(window.localStorage.getItem('start')):4
    const cloName = window.localStorage.getItem('cloName')?window.localStorage.getItem('cloName'):"sku"
    const activeSheet = window.wps.EtApplication().ActiveWorkbook.ActiveSheet
    // const value = window.wps.EtApplication().ActiveWorkbook.ActiveSheet.Cells.Item(4, 2).Value2

    const colRt = activeSheet.Cells.Item(1, activeSheet.Columns.Count).End(-4159).Column

    // 找到sku所在列
    let skuCol = 0
    for (let i = 1; i <= colRt; i++) {
        const value = activeSheet.Cells.Item(field, i).Value2
        if (value.includes(cloName)) {
            skuCol = i

            break;
        }
    }
    if (skuCol === 0) { alert("找不到sku列"); return }

    const lanRt = activeSheet.Cells.Item(activeSheet.Rows.Count, skuCol).End(-4162).Row


    let templateSheetName = ""

    for (let j = 1; j <= wps.EtApplication().Worksheets.Count; j++) {
        const item = wps.EtApplication().Worksheets.Item(j)
        if (item.Name.includes("Template") | item.Name.includes("模板")) {
            templateSheetName = item.Name
            break
        }
    }
    // 循环读取sku

    for (let i = start; i <= lanRt; i++) {
        const value = activeSheet.Cells.Item(i, skuCol).Value2
        if (!value) { break }

        let filePath = localStorage.getItem("filePath")
        filePath = filePath.replace(/\\/g, "\\\\")

        //根据sku判断文件是否存在，并打开 读取信息
        let path = filePath + "\\" + value + ".xlsm"

        wps.FileSystem.copyFileSync(wps.Application.ActiveWorkbook.FullName, path)

        let openBook = wps.Application.Workbooks.Open(path, 0)


        // for (let j = 4; j < i; j++) {
        //     openBook.Worksheets.Item(templateSheetName).Rows.Item(4).Delete()
        // }

        // for (let j = 1; j <= (lanRt - i); j++) {
        //     openBook.Worksheets.Item(templateSheetName).Rows.Item(5).Delete()

        // }

        if (i > start) {

            openBook.Worksheets.Item(templateSheetName).Range(`A${start}:A${i - 1}`).EntireRow.Delete()

        }
        if (lanRt >= (start+1)) {
            openBook.Worksheets.Item(templateSheetName).Range(`A${(start+1)}:A${lanRt}`).EntireRow.Delete()
        }


        openBook.Save()
        openBook.Close()


    }


}






function OnAction(control) {
    const eleId = control.Id
    switch (eleId) {
        case "btnRead":
            {
                const field = window.localStorage.getItem('field')?Number(window.localStorage.getItem('field')):3
                const start = window.localStorage.getItem('start')?Number(window.localStorage.getItem('start')):4
                const cloName = window.localStorage.getItem('cloName')?window.localStorage.getItem('cloName'):"sku"
                const sheet = window.wps.EtApplication().ActiveWorkbook.ActiveSheet

                // const lanRt = shObj.Range("A" + shObj.Rows.Count).End(-4162).Row


                const colRt = sheet.Cells.Item(field, sheet.Columns.Count).End(-4159).Column

                // 找到sku所在列
                let skuCol = 0
                for (let i = 1; i <= colRt; i++) {
                    const value = sheet.Cells.Item(field, i).Value2
                    if (value.includes(cloName)) {
                        skuCol = i

                        break;
                    }
                }

                if (skuCol === 0) { alert("找不到sku列"); break }

                const rowNumber = sheet.Cells.Item(sheet.Rows.Count, skuCol).End(-4162).Row


                // 循环读取sku

                for (let i = start; i <= rowNumber; i++) {

                    const value = sheet.Cells.Item(i, skuCol).Value2

                    if (!value) { break }

                    let filePath = localStorage.getItem("filePath")
                    filePath = filePath.replace(/\\/g, "\\\\") + "\\"
                    filePath=filePath + value + ".xlsm"
                    //根据sku判断文件是否存在，并打开 读取信息
                    let data = {}

                    if (wps.FileSystem.Exists(filePath)) {

                        const openBook = wps.EtApplication().Workbooks.Open(filePath, 0)

                        let templateSheetName = ""

                        for (let j = 1; j <= openBook.Worksheets.Count; j++) {
                            const item = openBook.Worksheets.Item(j)
                            if (item.Name.includes("Template") | item.Name.includes("模板")) {
                                templateSheetName = item.Name
                                break
                            }
                        }


                        if (templateSheetName) {
                            let templateSheet = openBook.Worksheets.Item(templateSheetName)

                            const tempColRt = templateSheet.Cells.Item(1, templateSheet.Columns.Count).End(-4159).Column

                            // 找到sku所在列


                            for (let c = 1; c <= tempColRt; c++) {
                                const item = templateSheet.Cells.Item(field, c).Value2
                                const value = templateSheet.Cells.Item(start, c).Value2
                                if (value) {
                                    data[item] = value
                                }

                            }
                            openBook.Close(false)

                        }



                    }


                    // 读取信息后，将信息写入到当前单元格

                    for (let index = 1; (index < colRt) & (Object.keys(data).length > 0); index++) {

                        if ((!sheet.Cells.Item(i, index).Value2) & (sheet.Cells.Item(field, index).Value2 in data)) {
                            sheet.Cells.Item(i, index).Value2 = data[sheet.Cells.Item(field, index).Value2]

                        }

                    }


                }







            }
            break;
        case "btnWrite":

            copyFile()
            break;

        case "btnSet":
            {
                Application.ShowDialog(
                  Util.GetUrlPath() + '/pathset',
                  '设置',
                  400 * window.devicePixelRatio,
                  500 * window.devicePixelRatio,
                  false
                )
            }
            break;
        case "btnWebRead":
            WriteSkuInfo()
            break;
        case "btnWebWrite":
            SaveSkuInfo()
            break
        default:
            break
    }
    return true
}

function GetImage(control) {
    const eleId = control.Id
    switch (eleId) {
        case "btnRead":
            return "images/1.svg"
        case "btnWrite":
            return "images/2.svg"
        case "btnSet":
            return "images/3.svg"
        case "btnWebRead":
            return "images/sync.svg"
        case "btnWebWrite":
            return "images/upload.svg"
    }
    return "images/newFromTemp.svg"
}

function OnGetEnabled(control) {
    const eleId = control.Id
    switch (eleId) {
        case "btnRead":
            return true
        case "btnWrite":

            return true
        default:
            break
    }
    return true
}

//这些函数是给wps客户端调用的
export default {
    OnAddinLoad,
    OnAction,
    GetImage,
    OnGetEnabled,
};
